#include "common.h"
#include "thread_func.hpp"

class ThreadData
{
public:
    std::string _name;
    func_t _func;
    pthread_mutex_t *_pmtx;
    pthread_cond_t *_pcond;

    ThreadData(const std::string name, func_t func, pthread_mutex_t *pmtx, pthread_cond_t *pcond)
        : _name(name),
          _func(func),
          _pmtx(pmtx),
          _pcond(pcond)
    {
    }
};

void *Entry(void *arg)
{
    ThreadData *td = (ThreadData *)arg;
    td->_func(td->_name, td->_pmtx, td->_pcond);
    delete td;
    return nullptr;
}

int main()
{
    // 定义互斥锁和条件变量
    pthread_mutex_t mtx;
    pthread_cond_t cond;
    // 初始化互斥锁和条件变量
    pthread_mutex_init(&mtx, nullptr);
    pthread_cond_init(&cond, nullptr);

    pthread_t tids[THREAD_NUM];
    for (int i = 0; i < THREAD_NUM; ++i)
    {
        std::string name = "child thread ";
        name += std::to_string(i + 1);
        ThreadData *td = new ThreadData(name, funcs[i], &mtx, &cond);
        pthread_create(tids + i, nullptr, Entry, (void *)td);
    }

    sleep(3);

    // 控制各子线程的执行顺序
    int cnt = 10;
    while (cnt--)
    {
        // std::cout << "condition signal! " << cnt << std::endl;
        // pthread_cond_signal(&cond);
        std::cout << "condition broadcast!" << std::endl;
        pthread_cond_broadcast(&cond);
        sleep(1);
    }

    quit = true;
    pthread_cond_broadcast(&cond);

    for (int i = 0; i < THREAD_NUM; ++i)
    {
        pthread_join(tids[i], nullptr);
        std::cout << "thread: " << tids[i] << " quit!" << std::endl;
    }

    // 销毁互斥锁和条件变量
    pthread_mutex_destroy(&mtx);
    pthread_cond_destroy(&cond);
    return 0;
}
